package com.xr.blackhoole.hystrix.callable;

import com.sun.corba.se.spi.orbutil.threadpool.Work;
import com.xr.blackhoole.mvc.context.BlackholeContext;
import com.xr.blackhoole.mvc.context.BlackholeContextHolder;

import java.util.concurrent.Callable;

public final class DelegatingBlackholeContextCallable<V> implements Callable<V> {

    private final Callable<V> delegate;
    // 用户信息上下文（根据项目实际情况定义ThreadLocal上下文）
    private BlackholeContext orginblackholeContext;

    public DelegatingBlackholeContextCallable(Callable<V> delegate, BlackholeContext orginblackholeContext) {
        this.delegate = delegate;
        this.orginblackholeContext = orginblackholeContext;
    }
    

    @Override
    public V call() throws Exception {
        //防止线程复用销毁ThreadLocal的数据
        BlackholeContextHolder.invalidContext();
        //将当用户的上下文设置进Hystrix线程的ThreadLoacl中
        BlackholeContextHolder.setContext(orginblackholeContext);
        try {
            return delegate.call();
        } finally {
            // 执行完毕，记得清理ThreadLocal资源
            BlackholeContextHolder.invalidContext();
        }
    }

    public static <V> Callable<V> create(Callable<V> delegate, BlackholeContext blackholeContext) {
        return new DelegatingBlackholeContextCallable<>(delegate, blackholeContext);
    }
}
